//
//  YWYoukuController.m
//  YueshengToutiao
//
//  Created by jun peng on 2022/5/22.
//  Copyright © 2022 YW. All rights reserved.
//

#import "YWYoukuController.h"
#import "YWDownloadController3.h"
#import "YWYoukuDetailController.h"

#import "YWKLineCheatsVideoListParam.h"
#import "YWKLineCheatsVideoListStatus.h"
#import "YWKLineCheatsVideoListResultStatus.h"
#import "YWKLineCheatsVideoListPageStatus.h"
#import "YWKLineCheatsVideoListDataStatus.h"
#import "YWKLineCheatsVideoListTool.h"
#import "YWKLineCheatsClassCell.h"
#import "YWDownloadManager3.h"
#import "YWNoContentView2.h"

@interface YWYoukuController ()<UITableViewDelegate,UITableViewDataSource,YWKLineCheatsClassCellDelegate,CAAnimationDelegate>

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *barConstraintHeight;
@property (weak, nonatomic) IBOutlet YWTableView *tableView;

@property(nonatomic,strong)NSMutableArray *statusArray;

@property(nonatomic,strong)NSMutableArray *imageViews;

@property (weak, nonatomic) IBOutlet UILabel *countLabel;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *countLabelWidthConstraint;
@end

@implementation YWYoukuController

-(NSMutableArray*)imageViews{

    if (_imageViews == nil) {
        _imageViews = [NSMutableArray array];
    }
    return _imageViews;
}


-(NSMutableArray *)statusArray{
    if (_statusArray == nil) {
        _statusArray = [NSMutableArray array];
    }
    return _statusArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navBar.title = @"优酷";
    self.barConstraintHeight.constant = self.navBar.frame.size.height;
    
    [self setupRightItem];
    //这里添加下拉控件
    MJWeakSelf
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{

        [weakSelf loadVideoNewData];
    }];
    [self.tableView.mj_header beginRefreshing];
    
    [self.view bringSubviewToFront:self.countLabel];
    self.countLabel.layer.cornerRadius = 8;
    self.countLabel.clipsToBounds = YES;
    self.countLabelWidthConstraint.constant = [self getWidthWithBtnContent:self.countLabel];
    
    
    [self setupLeftItem];
    
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getDownloadBadgeValue) name:YWGetDownloadBadgeValueNote object:nil];
    
    //监听通知改变KLineCheatsVideoListCell状态
         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeKLineCheatsVideoListTypeNote:) name:YWChangeKLineCheatsVideoListTypeNote object:nil];
}

-(void)changeKLineCheatsVideoListTypeNote:(NSNotification *)notification{
    
    NSString *videoUrl = notification.userInfo[YWVideoUrlKey];
    NSNumber *kLineCheatsVideoListTypeNum = notification.userInfo[YWKLineCheatsVideoListTypeKey];
    
    //这样遍历还是会卡一下的、但是我又不想用刷新的办法，那没办法了、除非你要像下载Manager一样Manager和VC引用同一个模型数组、引用同一个对象、单改Manager的模型数组
    for (YWKLineCheatsVideoListDataStatus *status in self.statusArray) {
        if ([status.VideoUrl isEqualToString:videoUrl]) {
            status.kLineCheatsVideoListType = kLineCheatsVideoListTypeNum.integerValue;
         
        }
    }
    
   
}


-(void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self getDownloadBadgeValue];
}

-(void)getDownloadBadgeValue{
    
    YWDownloadManager3 *manager = [YWDownloadManager3 sharedownloadManager];
    NSInteger count = [manager getDownloadingTaskCount];
    
        if (count > 0) {
            [self.countLabel setHidden:NO];
    
            self.countLabel.text = [NSString stringWithFormat:@"%ld", count];
    
            self.countLabelWidthConstraint.constant = [self getWidthWithBtnContent:self.countLabel];
    
        } else {
            [self.countLabel setHidden:YES];
        }
    
}

-(CGFloat)getWidthWithBtnContent:(UILabel*)label{
    
    NSString *content = label.text;
    UIFont *font = label.font;
    CGSize size = CGSizeMake(MAXFLOAT, 16.0f);
    CGSize buttonSize = [content boundingRectWithSize:size
                                              options:NSStringDrawingTruncatesLastVisibleLine  | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
                                           attributes:@{ NSFontAttributeName:font}
                                              context:nil].size;
    return buttonSize.width + 10;
}




-(void)loadVideoNewData{
    
    YWKLineCheatsVideoListParam *param = [[YWKLineCheatsVideoListParam alloc] init];
    
    if (self.meStatus.isLogin == YES) {
        param.phone = self.meStatus.userStatus.Phone;
    }
    else{
        param.phone = @"";
        
    }
    
    [YWKLineCheatsVideoListTool kLineCheatsVideoListStatusesWithParameters:param success:^(YWKLineCheatsVideoListStatus * _Nonnull status) {
        
        [self.noContentView removeFromSuperview];
        
               [self.tableView.mj_header endRefreshing];
        
               if (status.IsSuccess.integerValue == 1) {
                   
                   self.statusArray = [NSMutableArray arrayWithArray:status.ResultObj.PageInfo.VideoList];
                   
                
                   [self.tableView reloadData];
                   
                   
               }
               else{
                   
                   self.statusArray = [NSMutableArray array];
                   
                   [self.tableView reloadData];
                   
                   
                   
                   [self.view addSubview:self.noContentView];
                   
                   self.noContentView.frame = CGRectMake(0, 0, Wi, self.view.height);
                   
                   self.noContentView.noContentType = YWNoContentView2Type_NoContent;
                   
                   
                   
               }
        
    } failure:^(NSError * _Nonnull error) {
        
        [self.tableView.mj_header endRefreshing];
//              [MBProgressHUD showError:@"服务器繁忙，请稍后再试"];
        
        [self.view addSubview:self.noContentView];
        
        self.noContentView.frame = CGRectMake(0, 0, Wi, self.view.height);
        
        self.noContentView.noContentType = YWNoContentView2Type_Error404;
    }];
    

    
    
}

-(void)noContentView2DidClickRefreshBtn:(YWNoContentView2 *)noContentView2{
    
    [self.tableView.mj_header beginRefreshing];
    
}

-(void)setupRightItem{
    
    UIButton *rightItem = [[UIButton alloc] init];
    [rightItem setTitle:@"下载列表" forState:UIControlStateNormal];
    [rightItem setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//    [followBtn setImage:[UIImage imageNamed:@"消息关注"] forState:UIControlStateNormal];
    //    self.navBar.navBarTintColor = otherMainColor;
    rightItem.bounds = CGRectMake(0, 0, 180, 44);
    rightItem.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    //    locationBtn.imagei = UIEdgeInsetsMake(0, -10, 0, 0);
//    [followBtn setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 13)];
    [rightItem setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 8)];
    self.navBar.rightItem = rightItem;
    rightItem.titleLabel.font = [UIFont systemFontOfSize:14];
    [rightItem addTarget:self action:@selector(gotoDownloadList) forControlEvents:UIControlEventTouchUpInside];
}

-(void)gotoDownloadList{
    
    YWDownloadController3 *vc = [[YWDownloadController3 alloc] initWithNibName:@"YWDownloadController3" bundle:nil];
    [self.navigationController pushViewController:vc animated:YES];
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    YWKLineCheatsVideoListDataStatus *dataStatus = self.statusArray[indexPath.row];
    
    YWKLineCheatsClassCell *cell = [YWKLineCheatsClassCell cellWithTableView:tableView];
    cell.delegate = self;
    cell.status = dataStatus;
    return cell;

}
-(void)lineCheatsClassCellClickDownload:(YWKLineCheatsClassCell *)kLineCheatsClassCell withStatus:(YWKLineCheatsVideoListDataStatus *)status{
       
        [YWDownloadManager3 judgeStatusExistInDataBase:status.VideoUrl ifNoExist:^{
    
            YWDownloadManager3 *manager = [YWDownloadManager3 sharedownloadManager];
    
            YWDownloadStatus3 *dStatus = [[YWDownloadStatus3 alloc] init];
            dStatus.downloadType = YWDownloadType_Waiting3;
            dStatus.Title = status.Title;
            dStatus.PicUrl = status.PicUrl;
            dStatus.Id = status.Id;
            dStatus.VideoUrl = status.VideoUrl;
    
            [manager createOneDataTaskWithStatus:dStatus];
            
            //贝塞尔曲线动画
            [self berzierAnimationWithCell:kLineCheatsClassCell andIconView:kLineCheatsClassCell.iconView];
            
            //发送通知改变KLineCheatsVideoListCell状态
            [[NSNotificationCenter defaultCenter] postNotificationName:YWChangeKLineCheatsVideoListTypeNote object:self userInfo:@{YWVideoUrlKey:dStatus.VideoUrl,YWKLineCheatsVideoListTypeKey:@(YWKLineCheatsVideoList_Downloading3)}];
            
        }];
    
}

-(void)berzierAnimationWithCell:(UITableViewCell*)cell andIconView:(UIImageView *)iconView{
    
    //0、转换父控件所在位置
    CGRect rects = [cell.contentView convertRect:iconView.frame toView:[UIApplication sharedApplication].keyWindow];
    UIImageView *imageView = [[UIImageView alloc] init];
    imageView.contentMode = UIViewContentModeScaleAspectFill;
    imageView.clipsToBounds = YES;
    [[UIApplication sharedApplication].keyWindow addSubview:imageView];
    imageView.frame = rects;
    //用数组装着imageView,等动画结束就销毁imageView
    [self.imageViews addObject:imageView];
    imageView.image = iconView.image;
    if (iconView.image == nil) {
        imageView.image = [UIImage imageWithColor:YWColor(250, 250, 250)];
    }
    
    //1、圆角动画
    CABasicAnimation *cornerRadiusAnimation = [CABasicAnimation animation];
    cornerRadiusAnimation.keyPath = @"cornerRadius";
    cornerRadiusAnimation.fromValue = @(iconView.layer.cornerRadius);
    cornerRadiusAnimation.toValue = @(iconView.height/2);
//    [cornerRadiusAnimation setDuration:0.3];
//    [cornerRadiusAnimation setBeginTime:0.0];
    cornerRadiusAnimation.removedOnCompletion = NO;
    cornerRadiusAnimation.fillMode = kCAFillModeForwards;
    
    
//    CABasicAnimation *widthAnimation = [CABasicAnimation animation];
//    widthAnimation.keyPath = @"transform.scale.x";
//    widthAnimation.toValue = @(iconView.height*1.0/iconView.width);
//    [widthAnimation setDuration:0.3];
//    [widthAnimation setBeginTime:0.0];
//    widthAnimation.removedOnCompletion = NO;
//    widthAnimation.fillMode = kCAFillModeForwards;
    
    //2、曲线动画
    CGFloat desX = Wi - 50;
    CGFloat desY = self.navBar.height;
    CGPoint startPoint = CGPointMake(rects.origin.x+rects.size.width/2, rects.origin.y+rects.size.height/2);
    CGPoint endpoint = CGPointMake(desX, desY);
    //控制曲线弧度幅度的点
    CGPoint controlPoint = CGPointMake(Wi/2, He);
    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:startPoint];
    [path addQuadCurveToPoint:endpoint controlPoint:controlPoint];
    //创建关键帧
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    animation.path = path.CGPath;
//    [animation setDuration:0.6];
//    [animation setBeginTime:0.4];
    
    //3、创建缩放动画对象
    CABasicAnimation *scale = [CABasicAnimation animation];
    scale.keyPath = @"transform.scale";
    scale.toValue = @(0.1);
//    [animation setDuration:0.6];
//    [animation setBeginTime:0.4];

    //4、将所有的动画添加到动画组中
    CAAnimationGroup *group = [CAAnimationGroup animation];
    group.animations = @[/*widthAnimation,*/cornerRadiusAnimation,animation, scale];
    group.duration = 1;
    group.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    group.delegate = self;
    //当动画完成，停留到结束位置
    group.removedOnCompletion = NO;
    group.fillMode = kCAFillModeForwards;
    [imageView.layer addAnimation:group forKey:nil];
    path = nil;
    
}



#pragma mark - 动画的代理方法
-(void)animationDidStart:(CAAnimation *)anim{

}

-(void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{

   // 等动画结束就销毁第一个imageView，这样不会占内存了
   UIImageView *imageView = [self.imageViews firstObject];
    [imageView removeFromSuperview];
    [self.imageViews removeObject:imageView];

    NSLog(@"==%lu ==%lu",(unsigned long)self.view.window.subviews.count,(unsigned long)self.imageViews.count);
    
    
    //发送通知改badgeValue
    [[NSNotificationCenter defaultCenter] postNotificationName:YWGetDownloadBadgeValueNote object:self userInfo:nil];

}




/////--------/////--------/////--------/////--------/////--------/////--------/////--------/////--------/////--------/////









- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.statusArray.count;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 105;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    YWKLineCheatsVideoListDataStatus *dataStatus = self.statusArray[indexPath.row];
    
    
    YWYoukuDetailController *vc = [[YWYoukuDetailController alloc] initWithNibName:@"YWYoukuDetailController" bundle:nil];
    vc.status = dataStatus;
    [self.navigationController pushViewController:vc animated:YES];
    
    
}
//建立左边的item
-(void)setupLeftItem{
    
    UIButton *backBtn = [[UIButton alloc] init];
    [backBtn setImage:[UIImage imageNamed:@"icon-邮件认证"] forState:UIControlStateNormal];
    [backBtn setImage:[UIImage imageNamed:@"icon-邮件认证"] forState:UIControlStateHighlighted];
    backBtn.bounds = CGRectMake(0, 0, 100, 30);
    self.navBar.leftItem = backBtn;
    [backBtn addTarget:self action:@selector(askShow) forControlEvents:UIControlEventTouchUpInside];
    
    [backBtn setTitle:@"提示" forState:UIControlStateNormal];
    [backBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    backBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [backBtn setImageEdgeInsets:UIEdgeInsetsMake(0, 10, 0, 0)];
    [backBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 15, 0, 0)];
    backBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
}

-(void)askShow{
    
    YWAskView *askView = [YWAskView askView];
    askView.font = 13;
    askView.title = @"\
    1、数据存储方案：\
    1-1、“同一个文件夹”：装正在下载的文件和下载完成好的所有文件\
    1-2、“两个数据库的表格”：分别装下载的文件和下载完成好的文件\
    1-3、“字典”：装任务、“数组1”：装正在下载的任务、“数组2”：等待排队下载的任务（Manager）\
    1-4、枚举：\
    1-5、手动调用：枚举、数据库、通知写在Manager、、、回调调用：枚举、数据库、通知写在dataTaskStatus\n\
    2、顺序：\
    1、头一次 全新的 （不存在字典任务中、不存在数据库中、枚举waiting等待分配是否转变为枚举downloading）\
    2、正在下载重新进来 （存在字典任务中、存在数据库中、枚举downloading）\
    3、等待下载重新进来（存在字典任务中、存在数据库中、枚举waiting）\
    4、暂停重新进来（存在字典任务中、存在数据库中、枚举pause）\
    5、正在下载关了app再进来（不存在字典任务中、存在数据库中、枚举downloading）\
    6、等待下载关了app再进来（不存在字典任务中、存在数据库中、枚举waiting）\
    7、暂停关了app再进来（不存在字典任务中、存在数据库中、枚举pause）\n\
    3、Manager操作方法：\
    //app一进来就要调用开启任务了、获取数据库只有一次机会、就在这里\
    //在下载页VC的viewDidload调用、group有变化都会返回block、下载页VC只需要引用这个回传的group后直接刷新\
    //创建了一个任务\
    //继续一个任务 (包含按暂停和下载失败按钮)\
    //从等待中优先播放一个任务\n\
    //暂停一个任务\
    //删除了一个正在中的任务\
    //删除了一个完成了的任务\
    //判断这个模型存不存在数据库\n\
    4、最新方案：\
    1、枚举、数据库<为了退出app第二次打开获取上一次情况用的>、字典<任务字典>、数组2个<正在播放数组+等待中数组>、文件夹、group数组<为了打开app开始到app结束用的>、Tool操作\
    2、通知只用YWDownloadRefreshListNote、YWFinishDownloadNote、YWErrorDownloadNote\
    3、现在用的是Manager和VC共用模型数组group保证永远引用的是相同模型对象、这样Manager改变的group里的模型的属性(如currentSize)、VC引用的模型的属性也会跟着改变、然后再用通知去改变cell样式（这样模型和样式都有了、即VC就不要拥有group属性了、Manager拥有group属性、VC直接去用Manager的模型数组好了）";
    [askView show];
    
}
@end
